/*******************************************************************************
* file  : des demo
* creat : apleilx
* data  : 2017/03/02
* @brief  	des 是一种对称加密算法，加密解密主KEY相同
*			该算法以64bit或128bit为单元进行加密解密，密文和明文尺寸相同
*			本测试代码为64bit模式加密、解密验证
*			8字节KEY，8字节明文，8字节密文
*			不同版本的DES加密结果不同是正常的。
*			堆栈无要求
*******************************************************************************/
#include "common.h"
#include "crc_ext.h"
#include "mbedtls/des.h"
#include "bsp_api.h"
#include "sys_init.h"

/*******************************************************************************
* @brief  des_demo.
* \param[in] none
* \retval: none
*******************************************************************************/
void des_demo(void)
{
	uu32 clk_start;

	uu8 *src, *enc, *dec;
	mbedtls_des_context *mbed_des_enc;
	mbedtls_des_context *mbed_des_dec;

	// 内存请求
	src = calloc(1, 80);
	enc = calloc(1, 80);
	dec = calloc(1, 80);
	mbed_des_enc = calloc(1, sizeof(mbedtls_des_context));
	mbed_des_dec = calloc(1, sizeof(mbedtls_des_context));

	dbg_puts("\n===========================================================\n");
	dbg_print("mbed DES 64 test :\n");
	memcpy(src, led_code, 8);
	//memset(ptr, 0x53, 8);

	mbedtls_des_init(mbed_des_enc);
	mbedtls_des_init(mbed_des_dec);

	// mbed des key creat
	clk_start = bsp_cpu_clks_get();
	mbedtls_des_setkey_enc(mbed_des_enc, (void *)"12345678");
	mbedtls_des_setkey_dec(mbed_des_dec, (void *)"12345678");
	dbg_print("key make time: %d us\n", bsp_clks_to_us(bsp_cpu_clks_get() - clk_start));

	// enc dec
	clk_start = bsp_cpu_clks_get();
	mbedtls_des_crypt_ecb(mbed_des_enc, src, enc);
	mbedtls_des_crypt_ecb(mbed_des_dec, enc, dec);
	dbg_print("enc and dec time: %d us\n", bsp_clks_to_us(bsp_cpu_clks_get() - clk_start));

	// displsy
	dbg_u8_print("src: ", src, 8, 12);
	dbg_u8_print("enc: ", enc, 8, 12);
	dbg_u8_print("dec: ", dec, 8, 12);

	// 清除内存关键数据
	mbedtls_des_free(mbed_des_enc);
	mbedtls_des_free(mbed_des_dec);

	// 释放内存
	free(src);
	free(enc);
	free(dec);
	free(mbed_des_enc);
	free(mbed_des_dec);
}
